<template>
  <div class="default-main ba-table-box">
    <el-alert class="ba-table-alert"
              v-if="baTable.table.remark"
              :title="baTable.table.remark"
              type="info"
              show-icon />

    <!-- 表格顶部菜单 -->
    <TableHeader :buttons="['refresh', 'add', 'edit', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
                 :quick-search-placeholder="t('Quick search placeholder', { fields: '订单号' })">
      <template #shop>
        <el-select filterable
                   v-model="baTable.comSearch.form['shop_id']"
                   clearable>
          <el-option v-for="item in shop_arr"
                     :key="item.shop_id"
                     :label="item.shop_name"
                     :value="item.shop_id">
          </el-option>
        </el-select>
      </template>
      <template #orderId>
        <el-input v-model="baTable.comSearch.form['order_id']"
                  :rows="2"
                  type="textarea"
                  placeholder="请输入订单号" />
      </template>
    </TableHeader>

    <template style="display: block; margin-bottom: 10px;">
      <el-row :gutter="10"
              class="mb8"
              style="margin: 10px 0;">
        <el-col :span="1.5"
                v-if="baTable.auth('shippingDocuments')">
          <el-button type="primary"
                     @click="shippingDocumentsOperate">批量创建面单</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary"
                     @click="batchListShow">批次列表</el-button>
        </el-col>
        <el-col :span="1.5"
                v-if="baTable.auth('export')">
          <el-button type="warning"
                     @click="exportExcelOperate"
                     :loading="state.buttonLoading">
            <Icon :color="'#ffffff'"
                  name="el-icon-Position" />导出
          </el-button>
        </el-col>
        <el-col :span="1.5"
                v-if="baTable.auth('markerOrderDoc')">
          <el-button type="danger"
                     @click="markerOrderOperate">标记成已处理</el-button>
        </el-col>
      </el-row>
    </template>

    <el-tabs v-model="activeName"
             class="demo-tabs table-header ba-scroll-style"
             @tab-click="handleStatus"
             type="border-card">
      <el-tab-pane label="等待创建面单"
                   name="0"></el-tab-pane>
      <el-tab-pane label="正在创建中"
                   name="create_waybill_currently"></el-tab-pane>
      <el-tab-pane label="创建面单成功"
                   name="create_waybill_successfully"></el-tab-pane>
      <el-tab-pane label="创建面单失败"
                   name="create_waybill_failed"></el-tab-pane>
      <el-tab-pane label="创建pdf失败"
                   name="create_waybill_failed_pdf"></el-tab-pane>
      <el-tab-pane label="已处理"
                   name="waybill_processed"></el-tab-pane>
    </el-tabs>
    <!-- 表格 -->
    <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
    <Table />

    <!-- 表单 -->
    <PopupForm />
    <!-- 详情 -->
    <DetailCom :rowData="state.rowData" />
    <!-- 批次列表 -->
    <BatchCom ref="batchCom" />
  </div>
</template>


<script setup lang="ts">
import { provide, reactive, ref, onBeforeMount } from 'vue'
import baTableClass from '/@/utils/baTable'
import PopupForm from './popupForm.vue'
import DetailCom from './detailCom.vue'
import BatchCom from './batchCom.vue'
import Table from '/@/components/table/index.vue'
import TableHeader from '/@/components/table/header/index.vue'
import { defaultOptButtons } from '/@/components/table'
import { baTableApi, fileDownload } from '/@/api/common'
import { useAdminInfo } from '/@/stores/adminInfo'
import { useI18n } from 'vue-i18n'
import { ElMessage , type TabsPaneContext, ElMessageBox } from 'element-plus'
import { shippingDocuments, exportExcel, markerOrder } from '/@/api/backend/order/orderDocument'
import Cookies from 'js-cookie'
import { concat } from 'lodash-es'
import { getShopList } from '/@/api/backend/common'

defineOptions({
    name: 'order/orderDocument',
})

const { t } = useI18n()
const batchCom: any = ref<InstanceType<typeof BatchCom>>()
const adminInfo = useAdminInfo()
const activeName = ref('0')
const shop_arr = ref([] as any[])
const state: {
    buttonLoading: boolean,
    rowData: Object
} = reactive({
    buttonLoading: false,
    rowData: {}
})

let optButtons: OptButton[] = [
    {
        render: 'tipButton',
        name: '日志',
        title: '',
        text: '日志',
        type: 'info',
        icon: '',
        class: 'table-row-info',
        disabledTip: false,
        display: (row: TableRow, field: TableColumn) => {
            return baTable.auth('getLogInfo')
        },
        click: (row: TableRow) => {
            if(
                baTable.comSearch.form['status'] == 'create_waybill_successfully' || 
                baTable.comSearch.form['status'] == 'create_waybill_failed' || 
                baTable.comSearch.form['status'] == 'create_waybill_failed_pdf' 
            )
            {
                state.rowData = {...row}
                baTable.form.operate = 'detail'
            }else{
                ElMessage({
                    type: 'error',
                    message: '暂无日志，请先创建面单'
                })
            }
        }
    }
]
optButtons = concat(defaultOptButtons(['edit', 'delete']), optButtons)
optButtons[1].display = (row) => {
    return row.id != adminInfo.id
}

const baTable = new baTableClass(
    new baTableApi('/order/orderDocument/'),
    {
        column: [
            { type: 'selection', align: 'center', operator: false },
            {
                label: '店铺',
                prop:  'shop_id',
                operator: 'LIKE', 
                comSearchRender:'slot',
                comSearchSlotName: 'shop',
                show: false
            },
            {   
                label: '店铺', 
                prop: 'shop_name', 
                align: 'center',
                operator: false
            },
            {
                label: '订单号',
                prop:  'order_id',
                operator: 'LIKE', 
                align: 'center',
                comSearchRender:'slot',
                comSearchSlotName: 'orderId'
            },
            { label: t('order.orderDocument.skuinfo'), prop: 'skus_info', align: 'center', operator: 'LIKE', operatorPlaceholder: t('Fuzzy query') },
             { label: '创建时间(美国)', prop: 'createtime', align: 'center', render: 'datetime', sortable: 'custom', operator: false, width: 160 },
            {
                label: t('Operate'),
                align: 'center',
                width: '100',
                render: 'buttons',
                buttons: optButtons,
                operator: false
            }
        ],
        dblClickNotEditColumn: ['all']
    },
    {
        defaultItems: {
            status: '1',
        },
    }
)

provide('baTable', baTable)

baTable.mount()
baTable.getIndex()

const handleStatus = (tab: TabsPaneContext) => {
    // baTable.filter = {'status': tab.props.name}
    baTable.comSearch.form['status'] = tab.props.name
    const comSearchData: Array<any> = baTable.table.filter?.search || [];
    comSearchData.push({
        field: "status",
        val: tab.props.name,
        operator: "",
        render: "",
    })
    baTable.onTableAction('com-search', comSearchData)
}

const shippingDocumentsOperate = () => {
    let ids = baTable.getSelectionIds()
    if (!ids.length) {
        ElMessage ({
            type: 'error',
            message: '请选择订单',
        })
        return
    }

    // console.log(99999, ids, overseas_warehouse.value, golden_ant.value);
    // return
    const params = { ids: ids}
    shippingDocuments('post', params).then((res) => {
        baTable.toggleForm('')
        baTable.onTableHeaderAction('refresh', {})
    })
}

const exportExcelOperate = () => {
    state.buttonLoading = true
    baTable.table.loading = true
    ElMessageBox.confirm(
        '是否确认导出所有数据项?',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        type keymaps = {
            [key: string]: string | number
        }
        const obj:keymaps = {}
        baTable.table.filter?.search!.forEach(v => {
            obj[v.field] = v.val
        }) || []
        exportExcel('post', obj).then(response => {
            fileDownload(response, Cookies.get('filename') || 'file.xlsx')
        }).catch(err => {
            state.buttonLoading = false
            baTable.table.loading = false
        }).finally(() => { 
            state.buttonLoading = false
            baTable.table.loading = false
        })
    }).catch(() => {
        state.buttonLoading = false
        baTable.table.loading = false
    })
}

const markerOrderOperate = () => {
    let ids = baTable.getSelectionIds()
    if (!ids.length) {
        ElMessage ({
            type: 'error',
            message: '请选择订单',
        })
        return
    }

    const params = { ids: ids}
    markerOrder('post', params).then((res) => {
        baTable.toggleForm('')
        baTable.onTableHeaderAction('refresh', {})
    })
}
// 批次列表显示
const batchListShow = () => {
    batchCom.value.show = true
}

const getShopArr = () => {
    getShopList().then(res => {
        if(res.data && res.data.list.length) {
            shop_arr.value = res.data.list
        }
    })
}

onBeforeMount(async () => {
    getShopArr()
})

</script>

<style scoped lang="scss"></style>
